package com.qw.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.qw.gulimall.common.constant.AuthServerConstant;
import com.qw.gulimall.common.utils.R;
import com.qw.gulimall.common.vo.MemberResponseVo;
import com.qw.gulimall.auth.feign.MemberFeignService;
import com.qw.gulimall.auth.vo.GiteeTokenVo;
import com.qw.gulimall.auth.vo.GiteeUserVo;
import com.qw.gulimall.auth.vo.GiteeVo;
import com.qw.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * created by qw on 2022/8/5
 */
@Slf4j
@Controller
public class Oauth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        String url = "https://api.weibo.com/oauth2/access_token?client_id=1411893798&client_secret=6b03671f1d5bd30edcd63f029a38a428&grant_type=authorization_code&redirect_uri=http://auth.gulimall.com/oauth2.0/weibo/success&code=" +code;
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = httpClient.execute(httpPost);
        //2、处理
        if (response.getStatusLine().getStatusCode()==200){
            //获取到accessToken
            String json = EntityUtils.toString(response.getEntity());
            System.out.println(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道当前是哪个社交用户登录成功
            //1、当前用户如果是第一次进网站，就自动注册进来（为当前社交用户生成一个会员信息账号,以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            R r = memberFeignService.oauth2Login(socialUser);
            if (r.getCode()==0){
                MemberResponseVo memberResponseVo = r.getData(new TypeReference<MemberResponseVo>() {});
                System.out.println("登录成功，用户信息：" + memberResponseVo);
                log.info("登录成功，用户信息：" + memberResponseVo);
                //TODO 1、默认发的令牌 session=dadas,作用域只是当前域，（解决子域与父域session共享问题）
                //TODO 2、使用json的序列化方式来序列化对象数据到redis中
                session.setAttribute(AuthServerConstant.SESSION_LOGIN_KEY, memberResponseVo);
                //2、登录成功就跳回首页
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else{
            return "redirect:http://gulimall.com/login.html";
        }
    }

    @Value("${gitee.oauth2.clientid}")
    public String CLIENTID;
    @Value("${gitee.oauth2.clientsecret}")
    public String CLIENTSECRET;
    @Value("${gitee.oauth2.callback}")
    public String URL;

//    @ResponseBody
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception{
        //分局参数code获取token
        //https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code&code=" +code+"&client_id=" + CLIENTID+"&redirect_uri=" + URL+"&client_secret=" + CLIENTSECRET;
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = httpClient.execute(httpPost);
        //2、处理
        if (response.getStatusLine().getStatusCode()==200){
            //获取到accessToken
            String json = EntityUtils.toString(response.getEntity());
            System.out.println(response.getEntity());
            GiteeTokenVo giteeTokenVo = JSON.parseObject(json, GiteeTokenVo.class);
            String access_token = giteeTokenVo.getAccess_token();
            String urlGiteeUser = "https://gitee.com/api/v5/user?access_token="+access_token;
            HttpGet httpGet = new HttpGet(urlGiteeUser);
            HttpResponse responseGiteeUser = httpClient.execute(httpGet);
            if (responseGiteeUser.getStatusLine().getStatusCode()==200){
                String json1 = EntityUtils.toString(responseGiteeUser.getEntity());
                GiteeUserVo giteeUserVo = JSON.parseObject(json1, GiteeUserVo.class);
                //知道当前是哪个社交用户登录成功
                //1、当前用户如果是第一次进网站，就自动注册进来（为当前社交用户生成一个会员信息账号,以后这个社交账号就对应指定的会员）
                //登录或者注册这个社交用户
                GiteeVo giteeVo = new GiteeVo();
                giteeVo.setId(giteeUserVo.getId());
                giteeVo.setName(giteeUserVo.getName());
                giteeVo.setAvatar_url(giteeUserVo.getAvatar_url());
                giteeVo.setAccess_token(giteeTokenVo.getAccess_token());
                giteeVo.setExpires_in(giteeTokenVo.getExpires_in());
                giteeVo.setRefresh_token(giteeTokenVo.getRefresh_token());
                R r = memberFeignService.oauth2Login(giteeVo);
                if (r.getCode()==0){
                    MemberResponseVo memberResponseVo = r.getData(new TypeReference<MemberResponseVo>() {});
//                    System.out.println("登录成功，用户信息：" + memberRespVo);
                    log.info("登录成功，用户信息：" + memberResponseVo);
                    //TODO 1、默认发的令牌 session=dadas,作用域只是当前域，（解决子域与父域session共享问题）
                    //TODO 2、使用json的序列化方式来序列化对象数据到redis中
                    session.setAttribute(AuthServerConstant.SESSION_LOGIN_KEY, memberResponseVo);
                    //2、登录成功就跳回首页
                    return "redirect:http://gulimall.com";
                }else {
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            }else {
                return "redirect:http://gulimall.com/login.html";
            }
        }else{
            return "redirect:http://gulimall.com/login.html";
        }
    }

}
